<?php

namespace App\Http\Controllers\WorkOrder\Web;

use App\Enums\WorkOrder\OrderEnum;
use App\Events\WorkOrder\WorkOrderFinishEvent;
use App\Http\Controllers\BaseController;
use App\Http\Form\Form;
use App\Http\Middleware\OpenShop\FeishuWebAuth;
use App\Http\Validate\WorkOrder\Apply\ApplyValidate;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Rules\Mobile;
use App\Service\BaseService;
use App\Service\WorkOrder\Web\ApplyService;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class ApplyController extends BaseController
{

    /**
     * @param string $workOrderNo
     * @return JsonResponse
     * @throws ContainerExceptionInterface
     * @throws GuzzleException
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public function mainDetail(string $workOrderNo): JsonResponse
    {
        $userId = getRmsUserId();

        ApplyValidate::mainDetailValidate(["workOrderNo" => $workOrderNo]);
        return $this->success(ApplyService::mainDetail($workOrderNo, $userId));
    }

    /**
     * @param string $workOrderNo
     * @return JsonResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     * @throws Exception
     */
    public function contentDetail(string $workOrderNo): JsonResponse
    {
        ApplyValidate::mainDetailValidate(["workOrderNo" => $workOrderNo]);
        return $this->success(ApplyService::contentDetail($workOrderNo));
    }

    /**
     * 修改优先级
     *
     * @param Request $request
     * @param string $workOrderNo
     * @return JsonResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     * @throws Exception
     */
    public function updatePriority(Request $request, string $workOrderNo): JsonResponse
    {
        $params = ApplyValidate::updatePriorityValidate($request->merge(["workOrderNo" => $workOrderNo])->all());
        ApplyService::updatePriority($workOrderNo, $params->priority);
        return $this->success();
    }

    /**
     * 修改门店手机号
     *
     * @param Request $request
     * @param string $workOrderNo
     * @return JsonResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     * @throws Exception
     */
    public function updateShopMobile(Request $request, string $workOrderNo): JsonResponse
    {
        $params = ApplyValidate::updateShopMobileValidate($request->merge(["workOrderNo" => $workOrderNo])->all());
        ApplyService::updateShopMobile($workOrderNo, $params->mobile);
        return $this->success();
    }

    /**
     * @param Request $request
     * @param string $workOrderNo
     * @return JsonResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public function submitRemark(Request $request, string $workOrderNo): JsonResponse
    {
        $params = ApplyValidate::submitRemarkValidate($request->merge(["workOrderNo" => $workOrderNo])->all());
        ApplyService::submitRemark($params);
        return $this->success();
    }

    /**
     * @param Request $request
     * @param string $workOrderNo
     * @return JsonResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public function submitSolution(Request $request, string $workOrderNo): JsonResponse
    {
        $params = ApplyValidate::submitSolutionValidate($request->merge(["workOrderNo" => $workOrderNo])->all());
        ApplyService::submitSolution($params);
        return $this->success();
    }

    /**
     * @param Request $request
     * @param string $workOrderNo
     * @return JsonResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException|GuzzleException
     */
    public function submit(Request $request, string $workOrderNo): JsonResponse
    {
        $params = ApplyValidate::submitValidate($request->merge(["workOrderNo" => $workOrderNo])->all());
        ApplyService::submit($params->id);
        return $this->success();
    }

    /**
     * @param Request $request
     * @param string $workOrderNo
     * @return JsonResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     * @throws Exception
     */
    public function submitRemarkAndSolution(Request $request, string $workOrderNo): JsonResponse
    {
        $params = ApplyValidate::submitRemarkAndSolutionValidate($request->merge(["workOrderNo" => $workOrderNo])
                                                                         ->all());
        ApplyService::submitRemarkAndSolution($params->id, $params->remark, $params->solution ?? '');
        return $this->success();
    }

    /**
     * @param Request $request
     * @param string $workOrderNo
     * @return JsonResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     * @throws Exception
     */
    public function closeWorkOrder(Request $request, string $workOrderNo): JsonResponse
    {
        ApplyValidate::closeWorkOrderValidate($request->merge(["workOrderNo" => $workOrderNo])->all());
        $remark   = $request->post('remark', '');
        $solution = $request->post('solution', '');
        ApplyService::closeWorkOrder($workOrderNo, FeishuWebAuth::$userId, $remark, $solution);
        return $this->success();
    }

    /**
     * @param Request $request
     * @param string $workOrderNo
     * @return JsonResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     * @throws Exception
     */
    public function closeWorkOrderV2(Request $request, string $workOrderNo): JsonResponse
    {
        $params = ApplyValidate::closeWorkOrderV2Validate($request->merge(["workOrderNo" => $workOrderNo])->all());
        ApplyService::closeWorkOrderV2($params, FeishuWebAuth::$userId);
        return $this->success();
    }


    /**
     * 表单全量编辑
     *
     * @param Request $request
     * @param string $workOrderNo
     * @return JsonResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     * @throws Exception
     */
    public function renew(Request $request, string $workOrderNo): JsonResponse
    {
        //针对手机号校验
        $this->validate($request, [
            'formContent.driverPhone' => new Mobile(),
        ]);
        $params = ApplyValidate::updateContentValidate($request->merge(["workOrderNo" => $workOrderNo])->all());
        return $this->success(ApplyService::renew($workOrderNo, $params->formContent, FeishuWebAuth::$userId));
    }


    /**
     * 工单转交
     *
     * @param Request $request
     * @param string $workOrderNo
     * @return JsonResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     * @throws Exception
     */
    public function circulation(Request $request, string $workOrderNo): JsonResponse
    {
        ApplyValidate::circulationValidate($request->merge(["workOrderNo" => $workOrderNo])->all());
        //流转
        ApplyService::circulation($workOrderNo, $request->managerId, FeishuWebAuth::$userId);

        return $this->success();
    }

    /**
     * 获取门店套图列表
     * @param Request $request
     * @return JsonResponse
     * @throws Exception
     */
    public function shopImg(Request $request): JsonResponse
    {
        return $this->success(ApplyService::getShopImg());
    }

    /**
     * 修改门店套图列表
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     * @throws Exception
     */
    public function updateShopImg(Request $request): JsonResponse
    {
        $this->validate(
            $request, [
                'doorHeaderImg' => 'required|string|min:0',
                'frontImg'      => 'required|string|min:0',
            ]
        );
        if (empty($request->id)) {
            return BaseService::throwErr("id不能为空");
        }
        ApplyService::updateShopImg($request);
        return $this->success();
    }

    /**
     * 富友进件2.0-修改富友平台审核信息
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     * @throws Exception
     */
    public function updateFuyouInfo(Request $request): JsonResponse
    {
        $flagSuc = (int)$request->post('flagSuc', 0);
        if (!$flagSuc) {
            $this->validate(
                $request, [
                    'mchId'       => 'required|string|min:0|max:15',
                    'mchKey'      => 'string',
                    'orderPrefix' => 'string',
                    'mchName'     => 'required|string|min:0|max:128',
                    'mchPassword' => 'required|string|min:0|max:128',
                    'reservedFyTermId' => 'string',//富友终端号
                ]
            );
        }
        if (empty($request->id)) {
            return BaseService::throwErr("id不能为空");
        }
        ApplyService::updateFuyouInfo($request, $flagSuc);
        return $this->success();
    }

    /**
     * 富友进件2.0-重新发送邮件
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     * @throws Exception
     */
    public function sendFuyouEmail(Request $request): JsonResponse
    {
        $this->validate(
            $request, [
                'type' => 'required|integer|between:1,2',
            ]
        );
        if (empty($request->id)) {
            return BaseService::throwErr("id不能为空");
        }
        ApplyService::sendFuyouEmail($request->id, $request->type);
        return $this->success();
    }

    /**
     * 重置功能开通
     * @param Request $request
     */
    public function resetFunctionOpen(Request $request)
    {
        $problemChildIds = $request->post('problemChildIds');
        $shopId          = $request->post('shopId');
        $orderNo         = $request->post('orderNo');
        $unbind          = (int)(bool)$request->post('unbind', 0); // 1解绑

        if ($orderNo && !$shopId) {
            $shopId = (int)OpenShopMainProcessModel::query()->where('orderNo', $orderNo)->orderByDesc('id')
                                                   ->value('shopId');
            $request->merge(['shopId' => $shopId]);

            if (!$shopId) {
                BaseService::throwErr("不存在的orderNo");
            }
        }

        $this->validate($request, [
            'shopId'          => 'required|integer',
            "problemChildIds" => [
                'required',
                'array',
                function ($attribute, $value, $fail) {
                    foreach ($value as $val) {
                        if (!in_array($val, [
                            OrderEnum::PROBLEM_PID_5_CHILDREN_101,
                            OrderEnum::PROBLEM_PID_5_CHILDREN_102,
                            OrderEnum::PROBLEM_PID_5_CHILDREN_103,
                            OrderEnum::PROBLEM_PID_5_CHILDREN_104,
                            OrderEnum::PROBLEM_PID_5_CHILDREN_105,
                        ])) {
                            $fail("不允许的重置类型");
                        }
                    }
                }
            ]
        ]);

        $user = getRmsUserInfoByAuth();

        ApplyService::resetFunctionOpen($shopId, $problemChildIds, $unbind, $user->id, $user->username);

        return $this->success();
    }

    /**
     * 富友进件2.0-新增富友平台审核信息
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     * @throws Exception
     */
    public function addFuyouInfo(Request $request): JsonResponse
    {
        $flagSuc = (int)$request->post('flagSuc', 0);
        if (!$flagSuc) {
            $this->validate(
                $request, [
                    'mchId'       => 'required|string|min:0|max:15',
                    'mchKey'      => 'string',
                    'orderPrefix' => 'string',
                    'mchName'     => 'required|string|min:0|max:128',
                    'mchPassword' => 'required|string|min:0|max:128',
                    'reservedFyTermId' => 'string',//富友终端号
                ]
            );
        }
        if (empty($request->workOrderNo)) {
            return BaseService::throwErr("workOrderNo不能为空");
        }
        ApplyService::addFuyouInfo($request, $flagSuc);

        return $this->success();
    }
}
